package lg.minecraft.plugin.testeconomy.storage.model;

import lg.minecraft.plugin.testeconomy.TestEconomy;
import lg.minecraft.plugin.testeconomy.config.ManiConfig;
import lg.minecraft.plugin.testeconomy.storage.FileStorage;
import lg.minecraft.plugin.testeconomy.storage.StorageType;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author langle__
 * @version 1.0
 */
public class YAMLStorage extends FileStorage {

    private final File file;
    private final YamlConfiguration config;

    public YAMLStorage() {
        this.file = new File(TestEconomy.getManiConfig().getYmlPath());
        this.config = YamlConfiguration.loadConfiguration(this.file);
    }

    @Override
    public StorageType getType() {
        return StorageType.YAML;
    }

    @Override
    protected Double getMoney(String playerName) {
        return config.getDouble(playerName);
    }

    @Override
    protected void setMoney(String playerName, double amount) {
        config.set(playerName, amount);
        asyncSave();
    }

    @Override
    protected List<String> getPlayers() {
        return new ArrayList<>(config.getKeys(false));
    }

    @Override
    public void save() {
        try {
            this.config.save(this.file);
        } catch (IOException e) {
            TestEconomy.getInstance().getLogger().warning("Failed to save storage.yml");
        }
    }

    @Override
    public void load() {
        try {
            this.config.load(this.file);
        } catch (FileNotFoundException e) {
            TestEconomy.getInstance().getLogger().warning("storage.yml not found");
        } catch (IOException e) {
            TestEconomy.getInstance().getLogger().warning("Failed to load storage.yml");
        } catch (InvalidConfigurationException e) {
            TestEconomy.getInstance().getLogger().warning("Invalid configuration in storage.yml");
        }
    }

}
